<!DOCTYPE html>
<html>
<head>
  <title>🏠 系统首页 - 订单管理系统</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <style>
    :root {
      --primary-color: #4361ee;
      --secondary-color: #3f37c9;
      --success-color: #4cc9f0;
      --info-color: #4895ef;
      --warning-color: #f72585;
      --danger-color: #e63946;
      --light-color: #f8f9fa;
      --dark-color: #212529;
      --pending-color: #FF9800;
      --processing-color: #2196F3;
      --completed-color: #4CAF50;
      --cancelled-color: #F44336;
      --refunded-color: #9E9E9E;
      --on-hold-color: #9C27B0;
      --failed-color: #607D8B;
      --muted-color: #6c757d;
      --row-even-bg: #f8f9fa;
      --row-odd-bg: #ffffff;
    }
    
    body {
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      min-height: 100vh;
      max-width: 1440px;
      margin: 0 auto;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    
    .header-gradient {
      background: linear-gradient(120deg, var(--primary-color), var(--secondary-color));
      color: white;
      border-radius: 15px;
      box-shadow: 0 10px 30px rgba(0,0,0,0.15);
      margin-bottom: 25px;
      padding: 25px;
    }
    
    .welcome-card {
      background: white;
      border-radius: 15px;
      box-shadow: 0 10px 30px rgba(0,0,0,0.08);
      padding: 30px;
      margin-bottom: 25px;
      border: none;
      transition: all 0.3s;
    }
    
    .welcome-card:hover {
      box-shadow: 0 15px 40px rgba(0,0,0,0.15);
      transform: translateY(-3px);
    }
    
    .stat-card {
      border-radius: 15px;
      box-shadow: 0 10px 30px rgba(0,0,0,0.08);
      border: none;
      transition: all 0.3s;
      height: 100%;
    }
    
    .stat-card:hover {
      box-shadow: 0 15px 40px rgba(0,0,0,0.15);
      transform: translateY(-3px);
    }
    
    .stat-icon {
      width: 70px;
      height: 70px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 1.8rem;
      margin-bottom: 20px;
    }
    
    .order-card {
      cursor: pointer;
      transition: all 0.2s;
    }
    
    .order-card:hover {
      background-color: #e9f7fe !important;
    }
    
    .nav-link {
      color: rgba(255, 255, 255, 0.8) !important;
      font-weight: 500;
      transition: all 0.3s;
      border-radius: 5px;
      margin: 0 5px;
    }
    
    .nav-link:hover, .nav-link.active {
      color: white !important;
      background-color: rgba(255, 255, 255, 0.1);
    }
    
    .quick-link {
      text-decoration: none;
      color: inherit;
    }
    
    .quick-link:hover {
      text-decoration: none;
      color: inherit;
    }
    
    .quick-link-card {
      transition: all 0.3s;
      border-radius: 12px;
      height: 100%;
    }
    
    .quick-link-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 10px 25px rgba(0,0,0,0.15);
    }
    
    .status-badge {
      font-size: 0.9rem;
      padding: 5px 10px;
    }
    
    .table-container {
      background: white;
      border-radius: 15px;
      overflow: hidden;
      box-shadow: 0 10px 30px rgba(0,0,0,0.08);
    }
    
    .table th {
      background: linear-gradient(120deg, var(--primary-color), var(--secondary-color));
      color: white;
      font-weight: 600;
      padding: 15px;
    }
    
    .table td {
      padding: 15px;
      vertical-align: middle;
    }
    
    /* 交替行颜色 */
    .table-striped tbody tr:nth-of-type(even) {
      background-color: var(--row-even-bg);
    }
    
    .table-striped tbody tr:nth-of-type(odd) {
      background-color: var(--row-odd-bg);
    }
    
    .table-hover tbody tr:hover {
      background-color: #e9f7fe;
      transform: scale(1.01);
      transition: all 0.2s;
    }
    
    .badge-pending {
      background-color: var(--pending-color) !important;
    }
    
    .badge-processing {
      background-color: var(--processing-color) !important;
    }
    
    .badge-completed {
      background-color: var(--completed-color) !important;
    }
    
    .badge-cancelled {
      background-color: var(--cancelled-color) !important;
    }
    
    .badge-refunded {
      background-color: var(--refunded-color) !important;
    }
    
    .badge-on-hold {
      background-color: var(--on-hold-color) !important;
    }
    
    .badge-failed {
      background-color: var(--failed-color) !important;
    }
    
    .badge-muted {
      background-color: var(--muted-color) !important;
    }
    
    .tracking-badge {
      font-size: 0.85rem;
      padding: 5px 10px;
    }
    
    /* 商品信息列样式 */
    .product-info-column {
      width: 200px; /* 增加宽度 */
      font-size: 0.85rem; /* 缩小字体 */
    }
    
    .product-info-column small {
      font-size: 0.8rem; /* 进一步缩小字体 */
    }
    
    /* 新增悬停效果 */
    .hover-effect {
      transition: all 0.3s ease-in-out;
    }
    
    .hover-effect:hover {
      transform: translateY(-5px);
      box-shadow: 0 10px 20px rgba(0,0,0,0.15) !important;
    }
    
    /* 圆角优化 */
    .rounded-4 {
      border-radius: 1rem !important;
    }
    
    .rounded-top-4 {
      border-top-left-radius: 1rem !important;
      border-top-right-radius: 1rem !important;
    }
    
    .rounded-3 {
      border-radius: 0.75rem !important;
    }
    
    /* 动画效果 */
    @keyframes fadeInUp {
      from {
        opacity: 0;
        transform: translateY(20px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }
    
    .animate-card {
      animation: fadeInUp 0.5s ease forwards;
    }
    
    .animate-item {
      opacity: 0;
      animation: fadeInUp 0.5s ease forwards;
    }
    
    /* 为每个动画项设置延迟 */
    .animate-item:nth-child(1) { animation-delay: 0.1s; }
    .animate-item:nth-child(2) { animation-delay: 0.2s; }
    .animate-item:nth-child(3) { animation-delay: 0.3s; }
    .animate-item:nth-child(4) { animation-delay: 0.4s; }
    
    .animate-card:nth-child(1) { animation-delay: 0.1s; }
    .animate-card:nth-child(2) { animation-delay: 0.2s; }
    .animate-card:nth-child(3) { animation-delay: 0.3s; }
    .animate-card:nth-child(4) { animation-delay: 0.4s; }
    .animate-card:nth-child(5) { animation-delay: 0.5s; }
    .animate-card:nth-child(6) { animation-delay: 0.6s; }
    
    /* 数字动画 */
    .count-animation {
      transition: all 0.5s ease;
    }
  </style>
</head>
<body class="p-4">
  <div class="container-fluid">
    <div class="header-gradient">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <h1 class="mb-0"><i class="fas fa-home me-3"></i>🏠 系统首页</h1>
          <p class="mb-0 opacity-75">欢迎使用订单管理系统</p>
        </div>
        <div class="d-flex align-items-center">
          <nav class="navbar navbar-expand navbar-dark me-4">
            <div class="navbar-nav">
              <a class="nav-link active" href="/"><i class="fas fa-home me-1"></i> 系统首页</a>
              <a class="nav-link" href="/orders"><i class="fas fa-list me-1"></i> 订单管理</a>
              <a class="nav-link" href="/customers"><i class="fas fa-users me-1"></i> 客户管理</a>
              {% if current_user and current_user.role == "root" %}
              <a class="nav-link" href="/users"><i class="fas fa-user-cog me-1"></i> 用户管理</a>
              {% endif %}
            </div>
          </nav>
          {% if current_user %}
          <div class="dropdown">
            <button class="btn btn-light dropdown-toggle" type="button" id="userMenu" data-bs-toggle="dropdown">
              <i class="fas fa-user me-1"></i> {{ current_user.username }}
            </button>
            <ul class="dropdown-menu dropdown-menu-end">
              <li><a class="dropdown-item" href="/logout"><i class="fas fa-sign-out-alt me-2"></i>退出登录</a></li>
            </ul>
          </div>
          {% else %}
          <a class="btn btn-light" href="/login">
            <i class="fas fa-sign-in-alt me-1"></i> 登录
          </a>
          {% endif %}
        </div>
      </div>
    </div>

    <div class="welcome-card">
      <div class="row align-items-center">
        <div class="col-md-8">
          {% if current_user %}
          <h2 class="mb-3">👋 欢迎回来, {{ current_user.username }}!</h2>
          <p class="mb-0 lead">今天是 {{ "%.2f"|format(total_orders/1000) }}K 订单的时代，让我们一起高效管理您的业务。</p>
          {% else %}
          <h2 class="mb-3">👋 欢迎访问订单管理系统!</h2>
          <p class="mb-0 lead">这是一个功能强大的订单管理系统，帮助您高效管理业务。</p>
          {% endif %}
        </div>
        <div class="col-md-4 text-md-end">
          <div class="d-flex justify-content-md-end">
            <div class="text-center me-4">
              <div class="stat-icon bg-primary text-white rounded-circle">
                <i class="fas fa-boxes"></i>
              </div>
              <h4 class="mb-0">{{ total_orders }}</h4>
              <p class="text-muted mb-0">订单数</p>
            </div>
            <div class="text-center me-4">
              <div class="stat-icon bg-success text-white rounded-circle">
                <i class="fas fa-cube"></i>
              </div>
              <h4 class="mb-0">{{ total_items_sold }}</h4>
              <p class="text-muted mb-0">商品数</p>
            </div>
            <div class="text-center">
              <div class="stat-icon bg-info text-white rounded-circle">
                <i class="fas fa-users"></i>
              </div>
              <h4 class="mb-0">{{ unique_customers }}</h4>
              <p class="text-muted mb-0">客户数</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="row mb-4">
      <!-- 确保图表真正实现垂直居中 -->
      <!-- 订单统计区域 -->
      <div class="col-lg-9 mb-4">
        <div class="card stat-card shadow-sm h-100 border-0 rounded-4">
          <div class="card-header bg-white py-3 rounded-top-4">
            <h5 class="mb-0"><i class="fas fa-chart-bar me-2 text-primary"></i>订单统计</h5>
          </div>
          <div class="card-body">
            <div class="row g-3">
              <!-- 确保显示所有7种状态，包括已删除 -->
              {% set status_order = ['processing', 'completed', 'on-hold', 'cancelled', 'refunded', 'failed'] %}
              {% set status_labels = {
                'processing': '待处理',
                'completed': '已完成',
                'on-hold': '发货中',
                'cancelled': '已取消',
                'refunded': '已退款',
                'failed': '被拒收'
              } %}
              {% set status_colors = {
                'processing': 'primary',
                'completed': 'success',
                'on-hold': 'warning',
                'cancelled': 'danger',
                'refunded': 'secondary',
                'failed': 'dark'
              } %}
              
              {% for status_key in status_order %}
                <!-- 使用namespace来创建可修改的变量 -->
                {% set ns = namespace(count=0) %}
                {% for stat in status_stats %}
                  {% if stat.status == status_key %}
                    {% set ns.count = stat.count %}
                  {% endif %}
                {% endfor %}
                <div class="col-xl-4 col-lg-6 col-md-6 col-sm-12 animate-card">
                  <div class="card border-0 shadow-sm h-100 rounded-3 hover-effect">
                    <div class="card-body py-4">
                      <div class="d-flex justify-content-between align-items-center">
                        <h4 class="mb-0 text-{{ status_colors[status_key] }} fw-bold count-animation" data-count="{{ ns.count }}">{{ ns.count }}</h4>
                        <span class="badge bg-{{ status_colors[status_key] }} bg-opacity-10 text-{{ status_colors[status_key] }} rounded-pill px-3 py-2">
                          {{ status_labels[status_key] }}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              {% endfor %}
            </div>
          </div>
        </div>
      </div>
      
      <!-- 快速操作区域，确保图表真正垂直居中 -->
      <div class="col-lg-3 mb-4">
        <div class="card stat-card shadow-sm h-100 border-0 rounded-4">
          <div class="card-header bg-white py-3 rounded-top-4">
            <h5 class="mb-0"><i class="fas fa-bolt me-2 text-warning"></i>快速操作</h5>
          </div>
          <div class="card-body d-flex flex-column">
            <div class="d-grid gap-3 flex-grow-1">
              {% if current_user %}
              <a href="/orders" class="quick-link text-decoration-none">
                <div class="card border-primary border-2 shadow-sm quick-link-card h-100 rounded-3 hover-effect">
                  <div class="card-body py-3 d-flex align-items-center">
                    <div class="stat-icon bg-primary bg-opacity-10 text-primary rounded-circle d-inline-flex align-items-center justify-content-center me-3" style="width: 30px; height: 30px; flex-shrink: 0;">
                      <i class="fas fa-list"></i>
                    </div>
                    <div class="flex-grow-1">
                      <h6 class="mb-0 text-primary fw-bold">订单管理</h6>
                      <small class="text-muted">查看和管理所有订单</small>
                    </div>
                  </div>
                </div>
              </a>
              <a href="/customers" class="quick-link text-decoration-none">
                <div class="card border-success border-2 shadow-sm quick-link-card h-100 rounded-3 hover-effect">
                  <div class="card-body py-3 d-flex align-items-center">
                    <div class="stat-icon bg-success bg-opacity-10 text-success rounded-circle d-inline-flex align-items-center justify-content-center me-3" style="width: 30px; height: 30px; flex-shrink: 0;">
                      <i class="fas fa-users"></i>
                    </div>
                    <div class="flex-grow-1">
                      <h6 class="mb-0 text-success fw-bold">客户管理</h6>
                      <small class="text-muted">查看和管理客户信息</small>
                    </div>
                  </div>
                </div>
              </a>
              {% else %}
              <div class="card border-primary border-2 shadow-sm h-100 rounded-3">
                <div class="card-body py-3 d-flex align-items-center">
                  <div class="stat-icon bg-primary bg-opacity-10 text-primary rounded-circle d-inline-flex align-items-center justify-content-center me-3" style="width: 30px; height: 30px; flex-shrink: 0;">
                    <i class="fas fa-list"></i>
                  </div>
                  <div class="flex-grow-1">
                    <h6 class="mb-0 text-primary fw-bold">订单管理</h6>
                    <small class="text-muted">登录后查看和管理订单</small>
                  </div>
                </div>
              </div>
              <div class="card border-success border-2 shadow-sm h-100 rounded-3">
                <div class="card-body py-3 d-flex align-items-center">
                  <div class="stat-icon bg-success bg-opacity-10 text-success rounded-circle d-inline-flex align-items-center justify-content-center me-3" style="width: 30px; height: 30px; flex-shrink: 0;">
                    <i class="fas fa-users"></i>
                  </div>
                  <div class="flex-grow-1">
                    <h6 class="mb-0 text-success fw-bold">客户管理</h6>
                    <small class="text-muted">登录后查看和管理客户</small>
                  </div>
                </div>
              </div>
              <a href="/login" class="btn btn-primary">登录系统</a>
              {% endif %}
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="card stat-card">
      <div class="card-header bg-white">
        <div class="d-flex justify-content-between align-items-center">
          <h5 class="mb-0"><i class="fas fa-history me-2"></i>最近订单</h5>
          {% if current_user %}
          <button type="button" class="btn btn-outline-primary btn-sm" onclick="syncOrders()">
            <i class="fas fa-sync me-1"></i> 同步订单
          </button>
          {% endif %}
        </div>
      </div>
      <div class="card-body p-0">
        {% if recent_orders_list %}
        <div class="table-container">
          <table class="table table-striped table-hover mb-0">
            <thead>
              <tr>
                <th class="text-center" style="width: 100px;">订单编号</th>
                <th class="text-center" style="width: 150px;">订单状态</th>
                <th>客户信息</th>
                <th class="text-center product-info-column">商品信息</th>
                <th class="text-center" style="width: 80px;">数量</th>
                <th class="text-end" style="width: 120px;">订单金额</th>
                <th class="text-center" style="width: 120px;">下单时间</th>
                <th style="width: 120px;">来源站点</th>
              </tr>
            </thead>
            <tbody>
              {% for order in recent_orders_list %}
              <tr class="{% if current_user %}order-card{% endif %}" {% if current_user %}onclick="window.location.href='/order/{{ order.id }}'" style="cursor: pointer;"{% endif %}>
                <td class="text-center product-info-column">
                  <strong>#{{ order.order_id }}</strong>
                </td>
                <td class="text-center product-info-column">
                  {% if order.status == 'processing' %}
                    <span class="badge badge-pending"><i class="fas fa-clock me-1"></i> 待处理</span>
                  {% elif order.status == 'completed' %}
                    <span class="badge badge-completed"><i class="fas fa-check-circle me-1"></i> 已完成</span>
                  {% elif order.status == 'cancelled' %}
                    <span class="badge badge-cancelled"><i class="fas fa-times-circle me-1"></i> 已取消</span>
                  {% elif order.status == 'refunded' %}
                    <span class="badge badge-refunded"><i class="fas fa-undo me-1"></i> 已退款</span>
                  {% elif order.status == 'on-hold' %}
                    <span class="badge badge-on-hold"><i class="fas fa-pause-circle me-1"></i> 发货中</span>
                  {% elif order.status == 'failed' %}
                    <span class="badge badge-failed"><i class="fas fa-exclamation-triangle me-1"></i> 被拒收</span>
                  {% else %}
                    <span class="badge bg-secondary">{{ order.status }}</span>
                  {% endif %}
                  <!-- 显示物流信息 -->
                  {% if order.tracking_data %}
                    <div class="mt-2">
                      {% for tracking in order.tracking_data[:1] %}
                        <span class="badge bg-warning text-dark tracking-badge" title="运单号: {{ tracking.tracking_number }}">
                          <i class="fas fa-truck me-1"></i> {{ tracking.carrier_name }}
                        </span>
                      {% endfor %}
                      {% if order.tracking_data|length > 1 %}
                        <span class="badge bg-info tracking-badge">+{{ order.tracking_data|length - 1 }}</span>
                      {% endif %}
                    </div>
                  {% endif %}
                </td>
                <td>
                  <div>
                    {% if order.customer_email %}
                      <a href="/customer/{{ order.customer_email }}" style="color: #007bff; text-decoration: underline;">
                        {% if order.customer_first_name or order.customer_last_name %}
                          {{ order.customer_first_name }} {{ order.customer_last_name }}
                        {% else %}
                          {{ order.customer_name }}
                        {% endif %}
                      </a>
                    {% else %}
                      {% if order.customer_first_name or order.customer_last_name %}
                        {{ order.customer_first_name }} {{ order.customer_last_name }}
                      {% else %}
                        {{ order.customer_name }}
                      {% endif %}
                    {% endif %}
                  </div>
                  {% if order.customer_country %}
                    <small class="text-muted"><i class="fas fa-flag me-1"></i> {{ order.customer_country|country_name }}</small>
                  {% endif %}
                </td>
                <td class="text-center product-info-column">
                  {% if order.items %}
                    {% for item in order.items[:3] %}  <!-- 只显示前3个商品 -->
                      <div class="text-start">
                        <small>{{ item.name }}({% if item.meta_data %}{% for meta in item.meta_data %}{{ meta.value }}{% endfor %}{% endif %}) - {{ item.quantity }}</small>
                      </div>
                    {% endfor %}
                    {% if order.items|length > 3 %}
                      <div><small class="text-muted">+{{ order.items|length - 3 }} 更多</small></div>
                    {% endif %}
                  {% else %}
                    <small class="text-muted">-</small>
                  {% endif %}
                </td>
                <td class="text-center"><span class="badge bg-primary rounded-pill">{{ order.item_count }}</span></td>
                <td class="text-end">
                  <strong class="text-success">{{ "%.2f"|format(order.total) }} {{ order.currency }}</strong>
                </td>
                <td class="text-center product-info-column">
                  <small>{{ order.order_date.strftime('%Y-%m-%d %H:%M') if order.order_date else '-' }}</small>
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <span class="fw-bold">{{ order.source }}</span>
                    <small class="text-muted">{{ order.domain }}</small>
                  </div>
                </td>
              </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
        {% else %}
        <div class="text-center py-5">
          <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
          <p class="text-muted mb-0">暂无订单数据</p>
        </div>
        {% endif %}
      </div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    // 同步订单功能
    function syncOrders() {
      // 显示加载状态
      const syncButton = event.target.closest('button');
      const originalText = syncButton.innerHTML;
      syncButton.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> 同步中...';
      syncButton.disabled = true;
      
      // 发送同步请求
      fetch('/api/sync-orders', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        }
      })
      .then(response => {
        if (!response.ok) {
          throw new Error('同步失败');
        }
        return response.json();
      })
      .then(data => {
        if (data.success) {
          if (data.stats) {
            alert('订单同步完成！新增 ' + data.stats.inserted + ' 个订单，更新 ' + data.stats.updated + ' 个订单');
          } else {
            alert('订单同步完成！' + (data.details || '同步操作已成功执行，请刷新页面查看最新数据'));
          }
          // 同步成功，刷新页面
          location.reload();
        } else {
          throw new Error(data.message || '同步失败');
        }
      })
      .catch(error => {
        console.error('同步错误:', error);
        // 检查是否是Cloudflare防护相关的错误
        if (error.message && (error.message.includes('cloudflare') || error.message.includes('拦截'))) {
          alert('同步失败：请求被目标站点的安全防护拦截，请稍后重试。');
        } else {
          alert('同步失败: ' + error.message);
        }
        // 恢复按钮状态
        syncButton.innerHTML = originalText;
        syncButton.disabled = false;
      });
    }
    
    // 数字动画效果
    document.addEventListener('DOMContentLoaded', function() {
      const countElements = document.querySelectorAll('.count-animation');
      
      countElements.forEach(element => {
        const targetCount = parseInt(element.getAttribute('data-count'));
        const duration = 1000; // 动画持续时间（毫秒）
        const increment = targetCount / (duration / 16); // 每帧增加的数值
        let currentCount = 0;
        
        // 只对大于0的数字执行动画
        if (targetCount > 0) {
          const timer = setInterval(() => {
            currentCount += increment;
            if (currentCount >= targetCount) {
              currentCount = targetCount;
              clearInterval(timer);
            }
            element.textContent = Math.floor(currentCount);
          }, 16); // 约60fps
        }
      });
      
      // 触发动画元素的显示
      const animateItems = document.querySelectorAll('.animate-item, .animate-card');
      animateItems.forEach((item, index) => {
        item.style.opacity = '1';
      });
    });
  </script>
</body>
</html>